#include "detectionresult.h"

DetectionResult::DetectionResult() {}
DetectionResult::~DetectionResult() {}

void DetectionResult::SetInfo(ControlCommand &info)
{
    this->info = info;
}

void DetectionResult::SetResult(QList<DefectInfo> &result)
{
    this->result = result;
}

ControlCommand &DetectionResult::GetInfo()
{
    return this->info;
}

QList<DefectInfo> &DetectionResult::GetResult()
{
    return this->result;
}

bool DetectionResult::fromJson(const QString &json)
{
    QJsonParseError error;
    const QJsonDocument &detectResultRoot = QJsonDocument::fromJson(json.toUtf8().data(), &error);
    if (QJsonParseError::NoError == error.error) {
        const QJsonObject &detectResultObject = detectResultRoot.object();
        // 解析 info
        QJsonObject infoObject = detectResultObject.value(QStringLiteral("info")).toObject();
        info.FromJson(infoObject);

        // 解析 result
        const QJsonValue jsonResultValue = detectResultObject.value(QStringLiteral("result"));
        QJsonArray resultArray = jsonResultValue.toArray();

        result.clear();
        for (int i = 0; i < resultArray.size(); i++) {
            QJsonObject defectInfoObejct = resultArray.at(i).toObject();

            DefectInfo *pDefectInfo = new DefectInfo();
            pDefectInfo->FromJson(defectInfoObejct);

            result.append(*pDefectInfo);
        }
    } else {
        return false;
    }

    return true;
}

QString DetectionResult::toJson() const
{
    QJsonObject detectionResultObject;
    // info
    QJsonObject controlCommandObject;
    controlCommandObject.insert(QStringLiteral("cmd"), info.GetCmd());
    controlCommandObject.insert(QStringLiteral("seatnumber"), info.GetSeatNumber());
    controlCommandObject.insert(QStringLiteral("filename"), info.GetFileName());
    detectionResultObject.insert(QStringLiteral("info"), controlCommandObject);
    // result
    QJsonArray defectInfoArray;
    foreach (DefectInfo defectInfo, result) {
        QJsonObject defectInfoObject;
        defectInfoObject.insert(QStringLiteral("type"), defectInfo.GetType());

        QJsonObject rangeObject;
        rangeObject.insert(QStringLiteral("x"), defectInfo.GetRange().x());
        rangeObject.insert(QStringLiteral("y"), defectInfo.GetRange().y());
        rangeObject.insert(QStringLiteral("w"), defectInfo.GetRange().width());
        rangeObject.insert(QStringLiteral("h"), defectInfo.GetRange().height());

        defectInfoObject.insert(QStringLiteral("range"), rangeObject);

        defectInfoArray.append(defectInfoObject);
    }
    detectionResultObject.insert(QStringLiteral("result"), defectInfoArray);

    return QString(QJsonDocument(detectionResultObject).toJson(QJsonDocument::Compact));
}
